package cc.sunni.sleeve.manager.redis;

import cc.sunni.sleeve.bo.OrderMessageBO;
import cc.sunni.sleeve.service.CouponBackService;
import cc.sunni.sleeve.service.OrderCancelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

@Component
public class TopicMessageListener implements MessageListener {
    @Autowired
    private OrderCancelService orderCancelService;
    @Autowired
    private CouponBackService couponBackService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();

        String expiredKey = new String(body);
        String topic = new String(channel);

        // 通过不同的前缀做不同的处理
        if (expiredKey.startsWith("CANCEL,")) {
            String msg = expiredKey.replace("CANCEL,", "");
            OrderMessageBO messageBO = new OrderMessageBO(msg);
            orderCancelService.cancel(messageBO);
            couponBackService.returnBack(messageBO);
        }
    }
}
